package ifm4j.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XmlDomTransfer {
    private XmlDomTransfer() {
    }

    /**
     * Transfer DOM 2 XML file
     * 
     * @param filename
     */
    public static void transferDom2XmlFile(Document xdoc, String filename) {
        Transformer t = null;
        try {
            t = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            t = null;
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            t = null;
        }

        if (t == null) {
            return;
        }

        // set output properties
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        try {
            t.transform(new DOMSource(xdoc), new StreamResult(
                    new FileOutputStream(filename)));
        } catch (FileNotFoundException e) {
        } catch (TransformerException e) {
        }
    }

    public static Document transferXmlFile2Dom(String fileName) {
        File f = new File(fileName);
        DocumentBuilder builder;
        try {
            builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document xdoc = builder.parse(f);
            return xdoc;
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            return null;
        } catch (SAXException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }
}
